package cn.cdm.exception;

import cn.cdm.result.CodeMsg;
import cn.cdm.result.Result;
//import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@ControllerAdvice
@ResponseBody // 响应体的格式，方便输出
public class GlobalExceptionHandler {

	@ExceptionHandler(value=Exception.class)
	public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
		System.err.println("进入Web层全局异常处理：");
		if(e instanceof GlobalException) {
			GlobalException ex = (GlobalException)e;
			// 获取CodeMsg异常码信息
			return Result.error(ex.getCm());

		}else if(e instanceof BindException) {
			BindException ex = (BindException)e;
			List<ObjectError> errors = ex.getAllErrors();
			ObjectError error = errors.get(0);
			String msg = error.getDefaultMessage();
			return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));

		} else if(e instanceof DuplicateKeyException){
			return Result.error(CodeMsg.REPEAT_MIAOSHA);
		}
		else {
			log.error("异常信息：", e);
			return Result.error(CodeMsg.SERVER_ERROR);
		}
	}





	// 增加兜底异常
//	@ExceptionHandler(value = Exception.class)
//	public Result<String> exceptionHandle(HttpServletRequest request, Exception exception) {
////		System.out.println("进入兜底异常处理");
//		// 堆栈信息和错误码记录日志
//		String stackTrace = ExceptionUtils.getStackTrace(exception);
//		log.error(stackTrace);
//		Result result = Result.error(CodeMsg.SERVER_ERROR);
//		return result;
//	}

}







































